package com.uenpay.im.ui.old.activity.publicnumber;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.utils.Utils;
import com.qyx.android.database.TalkMsgManager;
import com.qyx.android.database.TopListMsgManager;
import com.qyx.android.message.type.BusinessCradType;
import com.qyx.android.message.type.OperationType;
import com.qyx.android.message.type.PacketType;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.chat.ActivityHandle;
import com.uenpay.im.ui.old.activity.chat.PickTalkActivity;
import com.uenpay.im.ui.old.activity.contacts.ReportContactsOrGroupActivity;
import com.uenpay.im.callback.IPopupWindowListener;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.PopupEntity;
import com.uenpay.im.entities.chatbean.MsgCradModel;
import com.uenpay.im.view.MyPopupWindow;
import com.uenpay.im.weight.RoundImageView;
import com.uenpay.util.app.base.BaseActivity;

import java.util.ArrayList;

/**
 * @author SL
 * @created 2016-1-8 上午11:42:27
 * @copyRight http://www.qiyunxin.com
 * @function 获取公众号详情
 */
public class PublicNumberDetailActivity extends BaseActivity {

    private ScrollView scroll_view;
    private TopListMsgManager topListMsgManager = new TopListMsgManager();
    private TalkMsgManager msgManager = new TalkMsgManager();
    private TextView publicNumberNameTv, publicNumberIntro,
            publicNumberAccountTv;
    private ImageView publicNumberReceiveMsgBtn;
    private RelativeLayout publicNumberViewMsgLayout, recv_msg_layout;
    private Button enter_btn, report_btn;
    private RoundImageView publicNumberAvatarIv;
    private View loading, recv_view;
    private String publicNumberId = "", cust_id = "";
    private int isfollow = 0, push = 0;
    private String publicNumName;
    private MyPopupWindow popupWindow = null;
    private PublicNumHandle mPublicNumHandle = new PublicNumHandle();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_publicnum_detail_layout;
    }

    @Override
    public void initView(View view) {
        publicNumberId = getIntent().getStringExtra("publicnoid");
        cust_id = getIntent().getStringExtra("cust_id");

        initView();
        initListener();
        if (TextUtils.isEmpty(publicNumberId)) {
            getPublicNumDetailInfo(cust_id, true);
        } else {
            getPublicNumDetailInfo(publicNumberId, false);
        }
        initPop();
    }

    protected void initView() {
        ((TextView) findViewById(R.id.title_textview)).setText(getResources()
                .getString(R.string.public_number));
        ((ImageView) findViewById(R.id.title_right_add_iv))
                .setImageResource(R.drawable.icon_more);
        publicNumberAvatarIv = (RoundImageView) findViewById(R.id.publicNumberAvatarIv);
        publicNumberNameTv = (TextView) findViewById(R.id.publicNumberNameTv);
        publicNumberIntro = (TextView) findViewById(R.id.publicNumberIntro);
        publicNumberAccountTv = (TextView) findViewById(R.id.publicNumberAccountTv);
        publicNumberReceiveMsgBtn = (ImageView) findViewById(R.id.publicNumberReceiveMsgBtn);
        publicNumberViewMsgLayout = (RelativeLayout) findViewById(R.id.publicNumberViewMsgLayout);
        recv_msg_layout = (RelativeLayout) findViewById(R.id.recv_msg_layout);
        report_btn = (Button) findViewById(R.id.report_btn);
        enter_btn = (Button) findViewById(R.id.enter_btn);
        loading = findViewById(R.id.loading);
        recv_view = findViewById(R.id.recv_view);
        scroll_view = (ScrollView) findViewById(R.id.scroll_view);
    }

    protected void initListener() {
        //返回键
        findViewById(R.id.back_layout).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
        enter_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (!TextUtils.isEmpty(publicNumberId)
                        || !TextUtils.isEmpty(cust_id))
                    if (isfollow == 1) {
                        sendMsg();
                    } else {
                        followPublicNum(isfollow, publicNumberId);
                    }
            }
        });
        report_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Bundle bundle = new Bundle();
                bundle.putInt("type", 1);
                bundle.putString("to_cust_id", publicNumberId);
                ActivityHandle.startActivity(PublicNumberDetailActivity.this,
                        ReportContactsOrGroupActivity.class, bundle, -1);
            }
        });

        publicNumberReceiveMsgBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (!TextUtils.isEmpty(publicNumberId)) {
                    if (push == 0) {
                        push = 1;
                    } else {
                        push = 0;
                    }
                    setPublicNumMsgPush(publicNumberId);
                }
            }
        });

        publicNumberViewMsgLayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (!TextUtils.isEmpty(publicNumberId))
                    if (isfollow == 1) {
                        sendMsg();
                    } else {
                        // TODO
                    }

            }
        });
        findViewById(R.id.title_right_iv_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        popupWindow.show(arg0);
                    }
                });
    }

    private ArrayList<PopupEntity> getPopData() {
        ArrayList<PopupEntity> arrayList = new ArrayList<PopupEntity>();
        PopupEntity entity = new PopupEntity(R.drawable.icon_share_publicnum,
                R.string.public_share, 1);
        PopupEntity entity1 = new PopupEntity(R.drawable.icon_popu_delete,
                R.string.public_clear_msg, 2);
        PopupEntity entity2 = new PopupEntity(R.drawable.icon_report_publicnum,
                R.string.complaints_friend, 3);
        PopupEntity entity3 = new PopupEntity(R.drawable.icon_cancel_follow_publicnum,
                R.string.public_cancel_follow, 4);
        arrayList.add(entity);
        arrayList.add(entity1);
        arrayList.add(entity2);
        arrayList.add(entity3);
        return arrayList;
    }

    private void initPop() {
        popupWindow = new MyPopupWindow(PublicNumberDetailActivity.this,
                getPopData(), new IPopupWindowListener() {

            @Override
            public void itemClick(int index) {
                if (index == 1) {
                    shareToFriend();
                } else if (index == 2) {
                    topListMsgManager.deleteByMsg(
                            Long.valueOf(cust_id), PacketType.PERSONAL);
                    msgManager.deleteSingleChatMsg(
                            Long.valueOf(cust_id),
                            Long.valueOf(IMApplication.getCustId()));
                    IMApplication.showToast(R.string.delete_success);
                } else if (index == 3) {
                    Intent intent = new Intent(
                            PublicNumberDetailActivity.this,
                            ReportContactsOrGroupActivity.class);
                    intent.putExtra("to_cust_id", publicNumberId);
                    intent.putExtra("type", 1);
                    startActivity(intent);
                } else {
                    if (!TextUtils.isEmpty(publicNumberId))
                        followPublicNum(1, publicNumberId);
                }
            }
        });
    }

    /**
     * 获取公众号详情
     *
     * @param publicid
     * @param isByCustId
     */
    private void getPublicNumDetailInfo(String publicid, boolean isByCustId) {
        loading.setVisibility(View.VISIBLE);
        mPublicNumHandle.getPublicNumDetail(publicid, isByCustId,
                new PublicNumHandle.IGetPublicNumListener() {

                    @Override
                    public void onGetPublicNumResult(int status, String msg,
                                                     PublicNumEntity publicNumEntity) {
                        myHandler.sendEmptyMessage(0);
                        if (status == HttpInvokeResultCode.RESULT_OK) {
                            scroll_view.setVisibility(View.VISIBLE);
                            push = publicNumEntity.push;
                            isfollow = publicNumEntity.isfollow;
                            cust_id = publicNumEntity.custid;
                            publicNumberId = publicNumEntity.publicnoid;
                            publicNumName = publicNumEntity.publicNumName;
                            cust_id = publicNumEntity.custid;
                            ((TextView) findViewById(R.id.title_textview))
                                    .setText(publicNumEntity.publicNumName);
                            publicNumberNameTv
                                    .setText(publicNumEntity.publicNumName);
                            publicNumberIntro.setText(publicNumEntity.fundesc);
                            publicNumberAccountTv
                                    .setText(publicNumEntity.accmbody);
                            publicNumberAvatarIv.SetUrl(APIConfiguration
                                    .getAvatarUrlNormal(publicNumEntity.custid,
                                            PacketType.PERSONAL));
                            if (push == 1) {
                                publicNumberReceiveMsgBtn
                                        .setImageResource(R.drawable.img_button_toggle_on);
                            } else {
                                publicNumberReceiveMsgBtn
                                        .setImageResource(R.drawable.img_button_toggle_off);
                            }
                            if (publicNumEntity.isfollow == 0) {
                                enter_btn.setText(getResources().getString(
                                        R.string.public_follow));
                                report_btn.setVisibility(View.GONE);
                                recv_msg_layout.setVisibility(View.GONE);
                                recv_view.setVisibility(View.GONE);
                                findViewById(R.id.title_right_iv_layout)
                                        .setVisibility(View.GONE);
                            } else {
                                findViewById(R.id.title_right_iv_layout)
                                        .setVisibility(View.VISIBLE);
                                enter_btn.setText(getResources().getString(
                                        R.string.public_account_enter));
                                report_btn.setVisibility(View.VISIBLE);
                                recv_msg_layout.setVisibility(View.VISIBLE);
                                recv_view.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                });

    }

    /**
     * 关注公众号
     *
     * @param type
     * @param publicNumId
     */
    private void followPublicNum(final int type, final String publicNumId) {
        loading.setVisibility(View.VISIBLE);
        mPublicNumHandle.followPublicNum(type, publicNumId,
                new PublicNumHandle.ISetPublicNumMsgPushListener() {

                    @Override
                    public void onSetPublicNumMsgPushResult(int status,
                                                            String msg) {
                        myHandler.sendEmptyMessage(0);
                        if (status == 0) {

                            if (type == 0) {
                                getPublicNumDetailInfo(publicNumId, false);
                                Intent intent = new Intent(
                                        BroadcastAction.REFRESH_PUBLIC_LIST_ACTION);
                                sendBroadcast(intent);
                            } else {
                                topListMsgManager.deleteByMsg(
                                        Long.valueOf(cust_id),
                                        PacketType.PERSONAL);
                                msgManager.deleteSingleChatMsg(Long
                                        .valueOf(cust_id), Long
                                        .valueOf(IMApplication.getCustId()));
                                Intent intent = new Intent(
                                        BroadcastAction.REFRESH_PUBLIC_LIST_ACTION);
                                sendBroadcast(intent);
                                finish();
                            }

                        }
                    }
                });

    }

    private void setPublicNumMsgPush(String publicNumId) {

        loading.setVisibility(View.VISIBLE);
        mPublicNumHandle.setPublicNumMsgPush(publicNumId, push,
                new PublicNumHandle.ISetPublicNumMsgPushListener() {

                    @Override
                    public void onSetPublicNumMsgPushResult(int status,
                                                            String msg) {
                        myHandler.sendEmptyMessage(0);
                        if (status == 0) {
                            if (push == 1) {
                                publicNumberReceiveMsgBtn
                                        .setImageResource(R.drawable.img_button_toggle_on);
                            } else {
                                publicNumberReceiveMsgBtn
                                        .setImageResource(R.drawable.img_button_toggle_off);
                            }

                        } else {
                            IMApplication.showToast(msg);
                        }
                    }
                });

    }

    public Handler myHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0) {
                if (loading != null) {
                    loading.setVisibility(View.GONE);
                }
            }
            return false;
        }
    });

    private void sendMsg() {
        /** 公众号信息OperationType==4 **/
        ActivityHandle.startChat(PublicNumberDetailActivity.this,
                Long.valueOf(cust_id), PacketType.PERSONAL,
                OperationType.PUBLIC_NUM, publicNumName, 0, null);
        finish();
    }

    private void shareToFriend() {
        // TODO
        MsgCradModel msgCradModel = new MsgCradModel();
        msgCradModel.setCradType(BusinessCradType.PUBLIC_NUM_CRAD);
        msgCradModel.setCustName(publicNumName);
        msgCradModel.setCustId(cust_id);
        Bundle bundle = new Bundle();
        bundle.putParcelable("forwardMsg", msgCradModel);
        Utils.startActivity(PublicNumberDetailActivity.this,
                PickTalkActivity.class, bundle);
    }
}